﻿using Newtonsoft.Json;
using Swimj.CommonLib.Base;

namespace Admin.RazorLib.Services
{
    public class FileService : IFileService
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public FileService(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<Result<string>> UploadFile(string bucketName, string fileName, Stream stream)
        {
            var httpClient = _httpClientFactory.CreateClient("adminApi");

            var multipartFormDataContent = new MultipartFormDataContent();
            multipartFormDataContent.Add(new StreamContent(stream), "file", fileName);
            var response =
                await httpClient.PostAsync($"api/v1/files/upload?bucketName={bucketName}", multipartFormDataContent);

            if (response.IsSuccessStatusCode)
            {
                var resultJson = await response.Content.ReadAsStringAsync();

                return JsonConvert.DeserializeObject<Result<string>>(resultJson);
            }

            return null;
        }
    }
}